<template>
  <div class="layout-container">
    <HsPhoneModel
    :materialList="materialList"
    :activeMaterialName="activeMaterialName"
    @handleConfirmPhoneModel="handleConfirmPhoneModel"
    material-type="example" />

    <view class="tabs hs-flex-center">
      <view class="nav-container">
        <view class="primary-nav">
          <view v-for="(item, index) in tabsList" :key="index" class="nav-item" @click="toggleSubNav(index)"
            :class="{ active: mainIndex === index }">
            {{ item.name }}
            <view class="hs-margin-row-10"
              :style="{ transform: `rotate(${mainIndex === index ? 90 : 0}deg)`, color: mainIndex === index ? '#3C4242' : '#807D7E' }">
              <image :src="`/static/images/icon/${mainIndex === index ? 'arrow-right-select' : 'arrow-right'}.png`"
                style="width: 35rpx;height: 35rpx;" mode="aspectFit"></image>
            </view>
          </view>
        </view>

        <view v-if="isShowSubNav" class="sub-nav">
          <view v-for="(subItem, i) in tabsList[mainIndex].children" :key="i" class="sub-nav-item"
            :class="{ 'sub-active': i === subIndex }" @click.stop="switchSubTab(subItem)"
            style="position: relative; z-index: 10;">
            {{ subItem.name }}
          </view>
        </view>
      </view>
    </view>
    <van-list
      v-model:loading="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="scrolltolower"
    >
      <!--  <van-cell v-for="(item, index) in 50" :key="index" :title="item" >
          {{ item }}
        </van-cell>-->
    </van-list>
  </div>
</template>
<script setup lang="ts">
  import { ref, computed,onMounted  } from "vue";
  import type {  MaterialListData } from "@/types/phoneInfo/index.ts";
  import type {  tabsData }  from "@/types/example.ts";
  import {  typeList, stickerList ,skuList} from "@/request/api";
  import { useRoute } from "vue-router";
  import { useExampleStore } from '@/stores';
  // 获取存储数据
  const exampleStore = useExampleStore(); // 获取历史记录
  const route = useRoute();
  let activePhoneModelId = ref<number>(35);//苹果16pro max
  let activeMaterial =  ref<number>(330);//镜面黑边
  let activeMaterialName = ref<string>("");
  let materialList = ref<MaterialListData[]>([]);
  let tabsList = ref<tabsData[]>([]);
  let mainIndex = ref<number>(0);
  let subIndex = ref<number>(0);
  let isShowSubNav = ref<boolean>(false);
  let listType = ref<number>(0);
  let algorithmName = ref<string>("");
  let loading = ref<boolean>(false);
  let finished = ref<boolean>(false);
  let pageSize = ref<number>(10);
  let exampleList = ref<any[]>([]);
  let lastSort = ref<number>(0); // 排序字段，默认按创建时间降序排序
  let styleIds = ref<number[]>([]); // 选择的风格列表
  const handleConfirmPhoneModel = (value: any) => {
    console.log('收到子组件传递的值:', value)
    // 这里可以处理机型变更后的逻辑
    activePhoneModelId.value = value.selectedOptions[value.selectedOptions.length - 1].value
    console.log('activePhoneModelId', activePhoneModelId.value)
    skuListFun(activePhoneModelId.value);
  };
  const toggleSubNav = (index: number) => {
    mainIndex.value = index;
    subIndex.value = 0;
    listType.value = tabsList.value[mainIndex.value].children[subIndex.value].type;
    algorithmName.value = tabsList.value[mainIndex.value].children[subIndex.value].algorithmName;
    isShowSubNav.value = true;
  }
  const switchSubTab = (subItem: tabsData) => {

    subIndex.value = subItem.index;
    listType.value = tabsList.value[mainIndex.value].children[subIndex.value].type;
    algorithmName.value = tabsList.value[mainIndex.value].children[subIndex.value].algorithmName;
    // getExampleList(); // 触发数据加载
  }


  // 通过默认选中的手机机型 获取默认机型对应的材质列表
  const skuListFun = async (activePhoneModelId?: number | null) =>    {
    let materialMap:any = {11: activePhoneModelId};
    let data = {
      pageSize: 50,
    }
    const response = await skuList(
      materialMap,
      data.pageSize,
    );
    console.log('skuList',response);
    materialList.value = response.data; // 更新材料列表数据 通过默认选中的手机机型 获取默认机型对应的材质列表
    const storedMaterial = exampleStore.exampleMaterial;
    let finalIndex = 0;
    console.log('response123',response);
    if (response?.code === 200) {
      const resData = response.data as MaterialListData[];
    console.log('resData',resData);

      if (resData.length > 0) {
        // 明确优先级：  历史记录 > 镜面黑边 > 默认项 > 首项
        // 使用可选链和空值合并操作符
        const historyMaterialId = storedMaterial?.materialMap?.[10]?? null; // 先查找历史记录
        // 分步查找策略
        finalIndex = resData.findIndex(
          (i:MaterialListData) => i.materialMap?.[10] === historyMaterialId
        );
        console.log('finalIndex', finalIndex);
        // 未找到历史材质时查找默认项为镜面黑边
        if (finalIndex === -1) {
          finalIndex = resData.findIndex((item:MaterialListData) =>
            item.name === '镜面黑边'
          );
        }
        // // 未找到历史材质时查找默认项
        // if (finalIndex === -1) {
        //   finalIndex = res.data.findIndex((item) => item.defaulted);
        // }

        // 双重保险：当默认项也不存在时取首项
        finalIndex = finalIndex >= 0 ? finalIndex : 0;

        finalIndex = Math.max(finalIndex, 0); // 确保下标不小于0
      }
      activeMaterial.value = resData[finalIndex].id;
      console.log('activeMaterial', activeMaterial.value);
      selectMaterial(resData[finalIndex]); // 选中默认材质项
    }

  }
  const selectMaterial = (item: MaterialListData) => {
    console.log('selectMaterial', item);
    activeMaterial.value = item.id; // 更新选中的材质ID
    activeMaterialName.value = item.name; // 更新选中的材质名称
    // materialList.value = resData; // 更新材料列表数据
    // console.log('materialList', materialList.value);
  }
  //材质
  const stickerListFun = async (lastSort?: number | null) => {
    let item = tabsList.value[mainIndex.value].children[subIndex.value];
    let materialMap:any = {10: activeMaterial.value,11: activePhoneModelId.value};
      // 添加参数验证
    let data = {
      materialMap,
      lastSort: lastSort || null, 
      type: item.type,
      algorithmName: item.algorithmName, // 使用响应式变量
      styleIds: styleIds.value.map(Number),
      pageSize: pageSize.value
    };
    const res = await stickerList(
        data.materialMap,
        data.lastSort,
        data.type,
        data.algorithmName,
        data.styleIds,
        data.pageSize
    ); // 获取材料列表
    console.log('stickerList',res);
  }
  //导航
  const typeListFun = async () => {
    const res = await typeList(); // 获取材料列表
    console.log('typeList',res);
    tabsList.value = res.data; // 更新材料列表数据
  }
  const scrolltolower = (e: Event) => {
    console.log(e);
    // if (this.exampleList.length < this.pageSize) return;
    //   console.log('scrolltolower', this.exampleList[this.exampleList.length - 1].sort),
    //     this.getExampleList(
    //       this.exampleList[this.exampleList.length - 1].sort
    //     );
  }

  onMounted(() => {
    // initData();
    typeListFun();
    skuListFun(activePhoneModelId.value);
    // stickerListFun();

  });
  
</script>
<style lang="scss" scoped>
  .tabs {
    margin: 0rpx auto 50rpx; //使列表往下移
    position: relative;
    width: 336rpx;

    .nav-container {
      position: relative;
      z-index: 10;

      .primary-nav {
        display: flex;
        justify-content: center;
        background: #fff;
        width: 100vw;

        .nav-item {
          padding: 20rpx 30rpx;
          font-size: 36rpx;
          position: relative;
          transition: all 0.3s;
          display: flex;
          flex-direction: row;

          &.active {
            color: #3C4242;
            font-weight: bold;
          }
        }
      }

      .sub-nav {
        position: absolute;
        top: 100%;
        left: 0;
        right: 0;
        background: #fff;
        box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
        padding: 5rpx 20rpx;
        display: flex;
        flex-wrap: wrap;

        .sub-nav-item {
          padding: 5rpx 24rpx;
          margin: 5rpx;
          background: #f5f5f5;
          border-radius: 40rpx;
          font-size: 26rpx;

          &:hover {
            background: #e0e0e0;
          }
        }

        .sub-active {
          background: #3C4242;
          color: white;

          // &::after {
          //   // content: '✓';
          //   margin-left: 8rpx;
          // }
        }
      }
    }

  }
</style>
